package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

var (
	file    = flag.String("file", "", "file to parse")
	imports = flag.String("imports", "", "imports")
	tplfile = flag.String("template", "template.tpl", "template file")
	suffix  = flag.String("suffix", "_gen.go", "generate suffix")
)

func main() {
	flag.Parse()
	if *file == "" {
		*file = os.Getenv("GOFILE")
		if *file == "" {
			fmt.Println("No file to parse")
			os.Exit(1)
		}
	}

	absfile, err := filepath.Abs(*file)
	if err != nil {
		fmt.Println("Invalid file", err)
	}

	filedir, filename := filepath.Split(absfile)
	importa := []string{}
	if len(strings.TrimSpace(*imports)) != 0 {
		importa = strings.Split(strings.Replace(*imports, " ", "", -1), ";")
	}

	fmt.Print(">>> Input: ", *file)

	defer func() {
		if err != nil {
			fmt.Println("\n \x1b[91mFailure\x1b[0m with error:", err)
			os.Exit(1)
		}
		fmt.Println(" \x1b[92mSuccess\x1b[0m")
	}()

	source := &Source{
		Filename: filename,
		Filedir:  filedir,
		Template: *tplfile,
		Suffix:   strings.Trim(*suffix, `"`),
		Imports:  importa,
	}

	p := NewParser(source)
	err = p.Parse()
	if err != nil {
		return
	}

	err = p.Print()
	if err != nil {
		return
	}
}
